<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\Config;

class Configuration extends Common
{
    private $table = 'config';

    public function update(): void
    {

        $field = Request::param('field');

        $val = Request::param('val');

        $info = Db::name($this->table)->where("name = '" . $field . "'")->find();

        if ($info) {
            Db::name($this->table)->where("name = '" . $field . "'")->update(array('val' => $val));
            $lastId = 1;
        } else {

            $lastId = Db::name($this->table)->insertGetId(array('val' => $val, 'name' => $field));

        }

//        $this->generateFile($field);

        singleJson($lastId, '出错');
    }

    public function detail(): void
    {

        $lists = Db::name('config')->select();

        $arr = array();
        foreach ($lists as $v) {
            $arr[$v['name']] = json_decode($v['val']);
        }

        singleJson($arr, '出错');
    }

    private function generateFile($field)
    {
        $info = Db::name($this->table)->where("name = '" . $field . "'")->find();

        $fileName = "../config/" . $field . ".php";

        $vals = json_decode($info['val'], true);

        $str = '<?php return [';

        foreach ($vals as $k => $v) {
            $str .= "'" . $k . "'" . "=>'" . $v . "',";
        }

        $str .= '];?>';

        file_put_contents($fileName, $str);
    }
}
